package com.itjob.deep.servlet;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.itjob.deep.bean.UserBean;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = -1763388443929755708L;

	@SuppressWarnings("unchecked")
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		
//		System.out.println(request.getParameter("username"));
		
		String username = URLDecoder.decode(request.getParameter("username"), "UTF-8");
		UserBean ub = new UserBean();
		ub.setUsername(username);
		ub.setGender(request.getParameter("gender"));
		ub.setLoginTime(System.currentTimeMillis());
		
		session.setAttribute("user", ub);
		
		Cookie cookie = new Cookie("user", URLEncoder.encode(username, "UTF-8"));
		cookie.setMaxAge(30000);
		
		response.addCookie(cookie);
		
		ServletContext application = this.getServletContext();
		Map<String, UserBean> users = (Map<String, UserBean>) application.getAttribute("users");
		
		if (users == null) {
			users = new HashMap<String, UserBean>();
			application.setAttribute("users", users);
		}
		
		users.put(username, ub);
		
		request.getRequestDispatcher("chat.jsp").forward(request, response);
		
	}
}
